<template>
  <el-dialog
    v-model="visible"
    v-if="load"
    title="修改推荐平台/站点"
    width="1200px"
    draggable
    @close="close"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :z-index="2000"
  >
    <vxe-grid v-bind="gridOptions">
      <template #product_identification="{ row }">
        <VGroup v-if="notAdd(row)" class="w-full">
          <SelectPlatformSite
            v-model:platform="row.platform_id"
            v-model:site="row.site_code"
            @changePlatform="changePlatform(row, $event)"
          >
          </SelectPlatformSite>
        </VGroup>
        <el-button v-if="row.type === 'add'" @click="handleAddRow"> +添加 </el-button>
      </template>
      <template #sales_price="{ row }">
        <el-input
          v-if="notAdd(row)"
          v-model.trim="row.sales_price"
          placeholder="请输入"
          clearable
        >
          <template #append>
            <select-currency
              class="w-24"
              v-model="row.currency_id"
              placeholder="币种"
              @change="changeCurrency(row, $event)"
            ></select-currency>
          </template>
        </el-input>
      </template>
      <template #competitor_link="{ row }">
        <el-input
          v-if="notAdd(row)"
          v-model="row.competitor_link"
          placeholder="请输入"
        ></el-input>
      </template>
      <template #header_channel_id="{ row }">
        <el-select
          v-if="notAdd(row)"
          v-model="row.header_channel_id"
          collapse-tags
          placeholder="选择"
          clearable
          class="w-full"
          @change="changeChannel(row, $event)"
        >
          <el-option
            v-for="item in channel_options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </template>
      <template #operation_user_ids="{ row }">
        <select-personnel
          v-if="notAdd(row)"
          class="w-full"
          v-model="row.operation_user_ids"
          :multiple="true"
          placeholder="请选择运营人员"
          @changeName="changeName(row, $event)"
        ></select-personnel>
      </template>
      <template #remark="{ row }">
        <el-input v-if="notAdd(row)" v-model="row.remark" placeholder="请输入"></el-input>
      </template>
      <template #operation="{ row, rowIndex }">
        <el-button type="danger" link v-if="notAdd(row)" @click="handleDelete(rowIndex)">
          删除
        </el-button>
      </template>
    </vxe-grid>
    <div>
      注：
      <p>
        1、修改所有绑定供应商：不勾选，则只修改‘默认供应商’的产品标识及加工说明数据；勾选后，修改该SKU绑定的所有供应商的产品标识及加工说明。
      </p>
      <p>2、新增：在勾选数据上新增维护的数据；</p>
      <p>3、覆盖：维护的数据覆盖所勾选SKU的产品标识及加工说明</p>
    </div>
    <template #footer>
      <div class="footer-btn flex items-center justify-center relative py-2">
        <div class="absolute left-0 top-0">
          <el-radio-group v-model="ids.type" class="ml-4">
            <el-radio :label="1">新增</el-radio>
            <el-radio :label="2">覆盖</el-radio>
          </el-radio-group>
        </div>
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="save">保 存</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="jsx">
import { ElMessage, ElMessageBox } from "element-plus";
import SelectPlatformSite from "@/components/SelectPlatformSite";
import { batchUpdateRecommend } from "../api.js";
import SelectCurrency from "@/components/SelectCurrency";
import { channel_options } from "@/utils/data.js";

const visible = ref(false);
const loading = ref(false);
const props = defineProps({
  options: {
    type: Object,
    default: () => {},
  },
});
const { options } = toRefs(props);
const ids = ref({
  type: 1,
});
const emit = defineEmits(["refresh"]);
const load = ref(false);
const open = async (data) => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  ids.value[data.name] = data.ids;
  visible.value = true;
};
const notAdd = (row) => row.type !== "add";
const gridOptions = reactive({
  round: true,
  height: "400",
  autoHidden: true,
  columnConfig: {
    resizable: true,
  },
  loading: false,
  data: [
    {
      type: "add",
    },
  ],
  columns: [
    {
      field: "product_identification",
      title: "平台/站点",
      align: "center",
      minWidth: 180,
      slots: { default: "product_identification" },
    },
    {
      field: "sales_price",
      title: "推荐销售价",
      align: "center",
      minWidth: 120,
      slots: { default: "sales_price" },
    },
    {
      field: "competitor_link",
      title: "竞品参考链接",
      align: "center",
      slots: { default: "competitor_link" },
    },
    {
      field: "header_channel_id",
      title: "建议头程渠道",
      align: "center",
      slots: { default: "header_channel_id" },
    },
    {
      field: "operation_user_ids",
      title: "运营人员",
      align: "center",
      slots: { default: "operation_user_ids" },
    },
    {
      field: "remark",
      title: "备注",
      align: "center",
      slots: { default: "remark" },
    },
    {
      title: "操作",
      width: 90,
      align: "center",
      slots: { default: "operation" },
    },
  ],
});
const handleAddRow = () => {
  gridOptions.data.splice(-1, 0, {
    currency_id: "USD",
  });
};
const handleDelete = (index) => {
  gridOptions.data.splice(index, 1);
};
const save = async () => {
  loading.value = true;
  try {
    let data = getTableData();
    const duplicates = checkDuplicate(data);
    if (duplicates.length > 0) {
      // duplicates.forEach(key => {
      //   const [platformId, siteCode] = key.split('_');
      //   console.log(`platform_id: ${platformId}, site_code: ${siteCode}`);
      // });
      // console.log(duplicates)
      ElMessageBox({
        title: "提示",
        message: () => (
          <div>
            {duplicates.map((key) => {
              const [platformId, siteCode] = key.split("_");
              return h("p", null, `平台：${platformId}/站点：${siteCode}已重复`);
            })}
          </div>
        ),
      });

      return;
    }
    if (!data?.length) return ElMessage.warning("请添加数据");
    const res = await batchUpdateRecommend(Object.assign({}, ids.value, { data: data }));
    if (res.code === 200) {
      ElMessage.success("操作成功");
      close(true);
    }
  } catch (error) {
    console.log(error);
  } finally {
    loading.value = false;
  }
};
const getTableData = () => {
  const data = gridOptions.data.filter((item) => item.type !== "add");
  return data;
};

const close = async (refresh) => {
  ids.value = {
    type: 1,
  };
  gridOptions.data = [
    {
      type: "add",
    },
  ];
  if (refresh) emit("refresh");
  visible.value = false;
};
defineExpose({ open });

const changePlatform = (item, val) => {
  item.platform_name = val;
};

const changeCurrency = (item, val) => {
  item.currency_name = val;
};

const changeChannel = (row, val) => {
  const item = channel_options.find((i) => i.value == val);
  if (item != undefined) {
    row.header_channel_name = item.label;
  }
};

const changeName = (item, val) => {
  item.operation_user_ids_text = val;
};

const checkDuplicate = (jsonData) => {
  const seen = new Set();
  const duplicates = new Set();

  for (const obj of jsonData) {
    const key = obj.platform_name + "_" + obj.site_code;
    if (seen.has(key)) {
      duplicates.add(key);
    } else {
      seen.add(key);
    }
  }

  return [...duplicates];
};
</script>
<style lang="scss" scoped>
.footer-btn {
  :deep(.el-button + .el-button) {
    margin-left: 8px !important;
  }
}
</style>
